﻿using UnityEngine;
using Interface;

namespace Client
{
    /// <summary>
    /// 界面挂件基类: 对应一个UIVisual，且被挂载到UIWindow的UIVisual的某个节点上
    /// </summary>
    public class UIWidget : UIBase
    {
        protected UIWidget(string uiKey) : base(uiKey)
        {
        }

        #region attach window
        protected UIWindow m_AttachedWindow;
        protected Transform m_AttachedNode;
        protected bool m_Attached;

        /// <summary>
        /// 设置挂载信息
        /// 参数有效性由UIManager保证
        /// </summary>
        /// <param name="window"></param>
        /// <param name="node"></param>
        public void SetAttachWindow(UIWindow window, Transform node)
        {
            Log.Debug("UIWidget.SetAttachWindow {0} {1} {2}", UIKey, window.UIKey, node.name);

            m_AttachedWindow = window;
            m_AttachedNode = node;
            m_Attached = false;
        }

        /// <summary>
        /// Window界面销毁，被Window界面移除
        /// </summary>
        public void DetachFromWindow()
        {
            Log.Debug("UIWidget.DetachFromWindow {0} {1}", UIKey, m_AttachedWindow.UIKey);

            DoDetachFromWindow(true);

            SetInUsing(false);
        }

        /// <summary>
        /// 断绝与Window界面的关联
        /// </summary>
        /// <param name="passive">是不是被Window界面断绝的</param>
        private void DoDetachFromWindow(bool passive)
        {
            Log.Debug("UIWidget.DoDetachFromWindow {0} {1} {2}", UIKey, m_Attached, InUsing);

            if (m_Attached)
            {
                if (!passive && m_AttachedWindow != null)
                {
                    m_AttachedWindow.OnWidgetDetached(this);
                }
                m_Attached = false;
                m_AttachedWindow = null;
                m_AttachedNode = null;

                if (passive && Visual != null)
                {
                    Visual.transform.SetParent(null);
                }
            }
        }
        #endregion

        #region override
        protected override void OnVisualLoaded()
        {
            base.OnVisualLoaded();

            Log.Debug("UIWidget.OnVisualLoaded {0} InUsing[{1}]", UIKey, InUsing);

            if (!InUsing)
            {
                return;
            }

            if (m_AttachedWindow == null || !m_AttachedWindow.InUsing || m_AttachedNode == null)
            {
                SetInUsing(false);
                return;
            }

            SetParent(m_AttachedNode);
            m_Attached = true;
            m_AttachedWindow.OnWidgetAttached(this);
        }

        protected override void DoSafeClear()
        {
            Log.Debug("UIWidget.DoSafeClear {0}", UIKey);

            DoDetachFromWindow(false);

            base.DoSafeClear();
        }
        #endregion
    }
}
